package com.conversationboard.api;

import static com.conversationboard.api.formatters.XmlWrapper.wrapCDATA;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.SecurityContext;

import com.conversationboard.api.formatters.XmlWrapper;
import com.conversationboard.api.security.Security;
import com.conversationboard.config.Configuration;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;

/* Input is <Boards></Boards> */

public class BoardsProcessor implements Processor {

	public String processXml(String xml, SecurityContext securityContext, HttpServletRequest request) throws ApiException {

		User user = null;
		List<Board> boards = null;

		try {
			if (Security.isLoggedIn(securityContext)) {

				user = User.get(securityContext.getUserPrincipal());
				boards = Boards.getAuthorisedBoards(user, false);
			} else {
				boards = Boards.getAuthorisedBoards(User.getAnonymousUser(), false);
			}
		} catch (SQLException e) {
			throw new ApiException(e);
		}

		return generateXML(boards, Configuration.getInstance().getRoot());
	}


	public static String generateXML(List<Board> boards, String contextPath) {

		StringBuilder buffer = new StringBuilder();

		buffer.append("<Boards>");

		for (Board board : boards) {
			buffer.append("<Board>");
			buffer.append("<BoardId>" + board.getBoardId() + "</BoardId>");
			buffer.append(wrapCDATA("Name", board.getName()));
			buffer.append(wrapCDATA("Description", board.getDescription()));
			buffer.append("<Private>" + XmlWrapper.convertBoolean(board.isPrivateBoard()) + "</Private>");
			buffer.append("<Popular>" + XmlWrapper.convertBoolean(board.isPopularBoard()) + "</Popular>");
			buffer.append("</Board>");
		}

		buffer.append("</Boards>");

		String xmlData = buffer.toString();

		return xmlData;
	}

}
